package com.platform.controller;

import java.math.BigDecimal;
import java.util.*;

import com.platform.entity.*;
import com.platform.service.*;
import com.platform.utils.push.UPush;
import org.apache.commons.lang3.RandomUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.platform.utils.PageUtils;
import com.platform.utils.Query;
import com.platform.utils.R;

/**
 * 会员、主播Controller
 *
 * @author zhurusen
 * @email 524227263@qq.com
 * @date 2018-06-03 11:20:12
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AmountBillService amountBillService;
    @Autowired
    private ApiCallBillService apiCallBillService;
    @Autowired
    private ApiMessageService apiMessageService;
    @Autowired
    private UserVideoService userVideoService;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 获取经人列表
     *
     * @param params
     * @return
     */
    @RequestMapping("/listAgent")
    @ResponseBody
    public R listAgent(@RequestParam Map<String, Object> params) {

        params.put("roleId", 3);
        List<SysUserEntity> apiUserList = sysUserService.queryList(params);

        return R.ok().put("list", apiUserList);
    }


    /**
     * 查看审核列表
     */
    @RequestMapping("/listAudlting")
    @RequiresPermissions("apiuser:list")
    @ResponseBody
    public R listAudlting(@RequestParam Map<String, Object> params) {

        if (params.get("type") != null) {
            if (params.get("invitationmobile") != null) {
                String invitationmobile = params.get("invitationmobile").toString();

                UserEntity userEntity = userService.selectByMobile(invitationmobile);
                if (userEntity != null) {
                    params.put("connection", userEntity.getId());
                } else {
                    params.put("connection", "0000000");
                }
            }
        }

        //查询列表数据
        Query query = new Query(params);

        List<UserEntity> apiUserList = userService.queryList(query);

        for (UserEntity info : apiUserList) {

            if (info.getMobile() != null) {
                info.setMobile(info.getMobile().substring(0, 3) + "****" + info.getMobile().substring(7, 11));
            }

            Long talkTimes = apiCallBillService.findSumTalkTimes(info.getId());
            info.setTalkTimes(talkTimes);

            params = new HashMap<>();
            params.put("userId", info.getId());
            params.put("type", 2);
            BigDecimal czAmoount = amountBillService.selectByUserIdAndType(params);
            info.setCzAmount(czAmoount);

            params = new HashMap<>();
            params.put("userId", info.getId());
            params.put("type", 1);
            BigDecimal xfAmoount = amountBillService.selectByUserIdAndType(params);
            info.setXsAmount(xfAmoount);

            params = new HashMap<>();
            params.put("zbUserId", info.getId());
            Integer ordernum = orderService.queryTotal(params);
            info.setOrdernum(ordernum);

        }

        int total = userService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(apiUserList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("apiuser:list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {

        if (params.get("type") != null) {
            if (params.get("invitationmobile") != null) {
                String invitationmobile = params.get("invitationmobile").toString();

                UserEntity userEntity = userService.selectByMobile(invitationmobile);
                if (userEntity != null) {
                    params.put("connection", userEntity.getId());
                } else {
                    params.put("connection", "0000000");
                }
            }
        }

        //查询列表数据
        Query query = new Query(params);

        List<UserEntity> apiUserList = userService.queryList(query);

        for (UserEntity info : apiUserList) {


            if (info.getMobile() != null) {
                info.setMobile(info.getMobile().substring(0, 3) + "****" + info.getMobile().substring(7, 11));
            }

            Long talkTimes = apiCallBillService.findSumTalkTimes(info.getId());
            info.setTalkTimes(talkTimes);

            params = new HashMap<>();
            params.put("userId", info.getId());
            params.put("type", 2);
            BigDecimal czAmoount = amountBillService.selectByUserIdAndType(params);
            info.setCzAmount(czAmoount);

            params = new HashMap<>();
            params.put("userId", info.getId());
            params.put("type", 1);
            BigDecimal xfAmoount = amountBillService.selectByUserIdAndType(params);
            info.setXsAmount(xfAmoount);

            params = new HashMap<>();
            params.put("zbUserId", info.getId());
            Integer ordernum = orderService.queryTotal(params);
            info.setOrdernum(ordernum);

        }

        int total = userService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(apiUserList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }


    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("apiuser:info")
    @ResponseBody
    public R info(@PathVariable("id") Long id) {
        UserEntity apiUser = userService.queryObject(id);

        String phone = "";
        if (apiUser.getMobile() != null) {
            phone = apiUser.getMobile().substring(0, 3) + "****" + apiUser.getMobile().substring(7, 11);
        }


        /**
         * 邀请量
         */
        Map<String, Object> params = new HashMap<>();
        params.put("connection", id);
        Integer yaoqingCount = userService.queryTotal(params);
        /**
         * 下单量
         */
        params = new HashMap<>();
        params.put("cmUserId", id);
        Integer orderCount = orderService.queryTotal(params);
        /**
         * 累计充值金额
         */
        params = new HashMap<>();
        params.put("userId", id);
        params.put("type", 2);
        BigDecimal cz_amount = amountBillService.selectByUserIdAndType(params);
        /**
         * 累计消费金额
         */
        params = new HashMap<>();
        params.put("userId", id);
        params.put("type", 1);
        BigDecimal xf_amount = amountBillService.selectByUserIdAndType(params);

        return R.ok().put("apiUser", apiUser).put("cz_amount", cz_amount).put("yaoqingCount", yaoqingCount).put("orderCount", orderCount).put("xf_amount", xf_amount).put("phone", phone);
    }

    /**
     * 封号
     */
    @RequestMapping("/suspend")
    @RequiresPermissions("apiuser:suspend")
    @ResponseBody
    public R suspend(@RequestBody Long id) {
        UserEntity userEntity = userService.queryObject(id);
        userEntity.setStatus(2L);
        userService.update(userEntity);
        return R.ok();
    }

    /**
     * 解封
     */
    @RequestMapping("/unsuspend")
    @RequiresPermissions("apiuser:suspend")
    @ResponseBody
    public R unsuspend(@RequestBody Long id) {
        UserEntity userEntity = userService.queryObject(id);
        userEntity.setStatus(1L);
        userService.update(userEntity);
        return R.ok();
    }


    /**
     * 查看信息
     */
    @RequestMapping("/audlting/{id}")
    @RequiresPermissions("apiuser:info")
    @ResponseBody
    public R audlting(@PathVariable("id") Long id) {
        UserEntity apiUser = userService.queryObject(id);
        String phone = "";
        if (apiUser.getMobile() != null) {
            phone = apiUser.getMobile().substring(0, 3) + "****" + apiUser.getMobile().substring(7, 11);
        }

        Map<String, Object> params = new HashMap<>();
        params.put("mouldId", id);
        params.put("type", 1);
        params.put("isShow", 0);
        List<ApiResourceEntity> pics = resourceService.queryList(params);
        return R.ok().put("apiUser", apiUser).put("picList", pics).put("phone", phone);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("apiuser:save")
    @ResponseBody
    public R save(@RequestBody UserEntity apiUser) {
        apiUser.setOlinetime(new BigDecimal(0));
        apiUser.setLive(1);

        List<ApiResourceEntity> res = apiUser.getPics();
        Integer rand = RandomUtils.nextInt(0, res.size());
        apiUser.setCoverUrl(res.get(rand).getUrl());
        userService.save(apiUser);
        return R.ok();
    }

    @RequestMapping("/audlt")
    @ResponseBody
    public R audlt(@RequestBody UserEntity apiUser) {

        UserEntity user = userService.queryObject(apiUser.getId());
        if (user != null) {
            user.setApplicationStatus(apiUser.getApplicationStatus());
            if (user.getApplicationStatus() != null && user.getApplicationStatus() == 3) {
                //审核成功
                ApiMessageEntity messageEntity = new ApiMessageEntity();
                messageEntity.setCreateTime(new Date());
                messageEntity.setTitle("审核成功");
                messageEntity.setContent("恭喜您认证成功（点击查看窝主守则）");
                messageEntity.setUserId(user.getId());

                apiMessageService.save(messageEntity);
                user.setIdentity(2);
                user.setLive(1);
//                UPush.push(user.getMobileType(), user.getDeviceToken(), "认证成功", "恭喜您认证成功");
            }

            if (user.getApplicationStatus() != null && user.getApplicationStatus() == 4) {
                //审核失败
                ApiMessageEntity messageEntity = new ApiMessageEntity();
                messageEntity.setCreateTime(new Date());
                messageEntity.setTitle("审核失败");
                messageEntity.setContent("您认证的窝主信息审核失败，请重新申请认证（点击查看窝主守则）");
                messageEntity.setUserId(user.getId());
                apiMessageService.save(messageEntity);

                user.setIdentity(1);
                user.setLive(2);
                user.setWake(2);
//                UPush.push(user.getMobileType(), user.getDeviceToken(), "认证失败", "您认证的窝主信息审核失败，请重新申请认证");
            }
        }
        userService.update(user);
        return R.ok();
    }


    /**
     * 修改
     */
    @RequestMapping("/audltUpdate")
    @RequiresPermissions("apiuser:update")
    @ResponseBody
    public R audltUpdate(@RequestBody UserEntity apiUser) {

        List<ApiResourceEntity> res = apiUser.getPics();
        if (res.size() > 0) {
            Integer rand = RandomUtils.nextInt(0, res.size());
            apiUser.setCoverUrl(res.get(rand).getUrl());
        }

        if (apiUser.getApplicationStatus() != null && apiUser.getApplicationStatus() == 3) {
            //审核成功
            ApiMessageEntity messageEntity = new ApiMessageEntity();
            messageEntity.setCreateTime(new Date());
            messageEntity.setTitle("审核成功");
            messageEntity.setContent("恭喜您认证成功（点击查看窝主守则）");
            messageEntity.setUserId(apiUser.getId());
            apiMessageService.save(messageEntity);
            apiUser.setIdentity(2);
            apiUser.setLive(1);
            UPush.push(apiUser.getMobileType(), apiUser.getDeviceToken(), "认证成功", "恭喜您认证成功");
        }

        if (apiUser.getApplicationStatus() != null && apiUser.getApplicationStatus() == 4) {
            //审核失败
            ApiMessageEntity messageEntity = new ApiMessageEntity();
            messageEntity.setCreateTime(new Date());
            messageEntity.setTitle("审核失败");
            messageEntity.setContent("您认证的窝主信息审核失败，请重新申请认证（点击查看窝主守则）");
            messageEntity.setUserId(apiUser.getId());
            apiMessageService.save(messageEntity);
            apiUser.setIdentity(1);
            apiUser.setLive(2);
            apiUser.setWake(2);
            UPush.push(apiUser.getMobileType(), apiUser.getDeviceToken(), "认证失败", "您认证的窝主信息审核失败，请重新申请认证");
        }

        userService.update(apiUser);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("apiuser:update")
    @ResponseBody
    public R update(@RequestBody UserEntity apiUser) {

        List<ApiResourceEntity> res = apiUser.getPics();
        if (res.size() > 0) {
            Integer rand = RandomUtils.nextInt(0, res.size());
            apiUser.setCoverUrl(res.get(rand).getUrl());
        }

        userService.update(apiUser);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("apiuser:delete")
    @ResponseBody
    public R delete(@RequestBody Long[] ids) {
        userService.deleteBatch(ids);
        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {
        List<UserEntity> list = userService.queryList(params);
        return R.ok().put("list", list);
    }


    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAllZb")
    @ResponseBody
    public R queryAllZb(@RequestParam Map<String, Object> params) {
        params.put("identity", 2);
        params.put("status", 1);
        List<UserEntity> list = userService.queryList(params);
        List<Map<String, Object>> reList = new ArrayList<>();
        for (UserEntity info : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", info.getId());
            map.put("name", info.getNickname());
            reList.add(map);
        }


        return R.ok().put("list", reList);
    }

}
